package com.jandan.web.front;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;

import com.jandan.logic.JWordzFacade;
import com.jandan.ui.model.Account;
import com.jandan.util.EncryptUtil;

/**
 * @author Gong Yong
 * @version 1.0
 */

public class SignonController implements Controller {
	private JWordzFacade jwordz;
	
	public void setJwordz(JWordzFacade jwordz) {
		this.jwordz = jwordz;
	}

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		
		
		String p = EncryptUtil.encryptPassword(password);
		Account account = jwordz.getAccount(userName, p);
		
		if (account == null) {
			return new ModelAndView("error", "message", "Invalid username or password.  Signon failed.");
		}
		else {
			UserSession userSession = new UserSession(account);
			request.getSession().setAttribute("userSession", userSession);
			request.getSession().setMaxInactiveInterval(-1);
			String forwardAction = request.getParameter("forwardAction");
			if (forwardAction != null) {
				response.sendRedirect(forwardAction);
				return null;
			}
			else {
				return new ModelAndView(new RedirectView("index.htm"));
			}
		}
	}
}
